package com.lyy.cloud.server.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;

/**
 * 授权解析拦截，origin参数预处理
 * @author liushiwei
 */
@Component
public class ServerSentinelRequestOriginParser implements RequestOriginParser {

    /**
     * 从给定的HTTP请求解析源代码。
     * @param request
     * @return
     */
    @SneakyThrows
    @Override
    public String parseOrigin(HttpServletRequest request) {
        // 判断header中是否有此参数
        String origin = request.getHeader("origin");

        // 判断请求参数中是否有此参数
        if(StringUtils.isBlank(origin)){
            origin = request.getParameter("origin");
        }

        if (StringUtils.isBlank(origin)) {
            // 或者自定义异常处理
            throw new AuthorityException("请求参数不合法");
        }
        return origin;
    }
}
